//index.js
//获取应用实例
const common = require("../../../../public.js")

Page({
  data: {
    currentTime: '',
    payBenefitMoney: '', // 支付钱
    payBenefitOrderNo: '', // 支付订单编号
    payBenefitOrderId: '', // 支付订单id
    payStatus: false, // 没有获取到支付状态,就显示支付页面，否则就显示 回到app界面
    paySuccess: false,
    fromSmallProgramm: false,
    isLoading: false
  },
  onLoad: function (options) {
    if (options.fromSmallProgramm) {
      this.setData({
        fromSmallProgramm: true
      })
    }
    this.data.payBenefitMoney = options.payBenefitMoney ? options.payBenefitMoney : '0.00';
    this.data.payBenefitOrderNo = options.payBenefitOrderNo ? options.payBenefitOrderNo : 'aaaa';
    this.data.payBenefitOrderId = options.payBenefitOrderId ? options.payBenefitOrderId : 'bbbb';
    this.setData({
      payBenefitMoney: this.data.payBenefitMoney,
    })

    var date = new Date() //现在时间
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    this.data.currentTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second
    this.countDown()
  },
  //倒计时
  countDown() {
    var that = this
    var date = new Date(); //现在时间
    // var starttime = '2020/06/05 09:04:19'
    // var start = new Date(starttime.replace(/-/g, "/")).getTime()
    var start = new Date(that.data.currentTime).getTime()
    var endTime = start + 30 * 60000 // 60000毫秒=60秒=1分钟
    var now = date.getTime(); //现在时间戳
    //  = 截止时间-当前时间
    var allTime = endTime - now
    var h, m, s;
    if (allTime > 0) { // 没结束
      // console.log("没结束");
      // 小时
      h = Math.floor(allTime / 1000 / 60 / 60 % 60);
      // console.log('h为',h);
      if (h < 10) {
        h = '0' + h;
      }

      // 分钟
      m = Math.floor(allTime / 1000 / 60 % 60);
      if (m < 10) {
        m = '0' + m;
      }
      // 秒
      s = Math.floor(allTime / 1000 % 60);
      if (s < 10) {
        s = '0' + s;
      }
      that.setData({
        countDown: h + '：' + m + "：" + s,
      })
      setTimeout(that.countDown, 1000);
    } else { // 结束了
      that.setData({
        countDown: '00:00:00'
      })
    }
  },

  onShow: function () {

  },
  surePayClick: common.throttleFunc(function (e) {
    const that = this
    wx.getStorage({
      key: 'user',
      success: function (res) {
        that.setData({
          userInfo: res.data.user,
          token: res.data.token,
          openid: res.data.openid
        })
        that.goToPay()
      },
      fail: function (res) {
        that.loginDeal()
      }
    })
  }, 3000),

  loginDeal() {
    const that = this
    common.loginFunc().then(res => {
      that.resetSurePayClick()
    })
  },
  goToPay() {
    const that = this
    this.setData({
      isLoading: true
    })

    var tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      orderId: that.data.payBenefitOrderId ? that.data.payBenefitOrderId : '6517',
      xcxOpenid: that.data.openid,
    }
    common.wxPayRequest("/wxxcxPayForBenefitGoods", tempJson, function (res) {
      wx.hideLoading()
      if (res.status == 200) {
        //微信支付
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (res) {
            common.showToast('支付成功', 'success')

            if (that.data.fromSmallProgramm == true) { // 从小程序支付页面跳转
              console.log('小程序跳转到的');
              that.setData({
                paySuccess: true,
              })
              that.popPage();
            } else {
              console.log('app跳转到的');
              that.setData({
                payStatus: true,
                paySuccess: true,
              })
            }
          },
          'fail': function (res) {
            console.log("提交失败")
            if (res.errMsg === 'requestPayment:fail cancel') {
            } else {
              common.showToast(res.errMsg)
            }
            if (that.data.fromSmallProgramm == true) { // 从小程序支付页面跳转
              console.log('小程序跳转到的');
              that.setData({
                paySuccess: false,
              })
              that.popPage();
            } else {
              console.log('app跳转到的');
              that.setData({
                payStatus: true,
                paySuccess: false,
              })
            }
          }
        })
      } else {
        common.showRequestErrMsg(res)
      }
    }, function () {
      that.setData({
        isLoading: false
      })
    })
  },
  resetSurePayClick() {
    const that = this
    wx.getStorage({
      key: 'user',
      success: function (res) {
        that.setData({
          userInfo: res.data.user,
          token: res.data.token,
          openid: res.data.openid
        })
        // that.loginDeal();
        that.goToPay()
      },
      fail: function (res) {
        common.showToast('没有用户信息')
        that.loginDeal()
      }
    })
  },
  launchAppError(e) {
    common.showToast(e.detail.errMsg)
  },
  // 返回指定界面
  popPage: function () {
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 3]; // 返会上个界面
    // prevPage.setData({// 返回携带参数给上个界面
    //   invoiceId: dataId
    // });
    wx.navigateBack({ // 返会上个界面
      delta: 2
    })

  },
})